from celery import shared_task
from celery.schedules import crontab
from django.utils import timezone
from django_cryptography.fields import encrypt
import random
import string
import subprocess
from .models import Host, HostStatistics, City, DataCenter


@shared_task
def change_host_passwords():
    """每8小时更改所有主机的root密码"""
    hosts = Host.objects.all()
    for host in hosts:
        # 生成12位随机密码
        new_password = ''.join(random.choices(
            string.ascii_letters + string.digits + '!@#$%^&*',
            k=12
        ))
        host.root_password = encrypt(new_password)
        host.last_password_change = timezone.now()
        host.save()
    return f"Changed passwords for {hosts.count()} hosts"


@shared_task
def generate_host_statistics():
    """每天00:00生成主机统计"""
    today = timezone.now().date()
    cities = City.objects.all()

    for city in cities:
        data_centers = city.data_centers.all()
        for dc in data_centers:
            host_count = dc.hosts.count()
            HostStatistics.objects.create(
                date=today,
                city=city,
                data_center=dc,
                host_count=host_count
            )
    return "Generated host statistics"


@shared_task
def check_hosts_reachable():
    """定期检查主机可达性"""
    hosts = Host.objects.all()
    for host in hosts:
        try:
            result = subprocess.run(['ping', '-c', '1', '-W', '1', host.ip_address],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            host.is_reachable = result.returncode == 0
            host.last_reachable_check = timezone.now()
            host.save()
        except:
            continue
    return f"Checked reachability for {hosts.count()} hosts"